package initcation

import (
	"day12_12_homework/pkg"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
	"time"
)

type MessageChat struct {
	Contents string `json:"contents"`
}

var (
	upgrade = websocket.Upgrader{
		//允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	//websocket 长连接
	wsConn *websocket.Conn
	conn   *pkg.Connection
	data   []byte
)

func WsHandlers(c *gin.Context) {
	//header中添加Upgrade:websocket
	if wsConn, err = upgrade.Upgrade(c.Writer, c.Request, nil); err != nil {
		return
	}

	if conn, err = pkg.InitConnection(wsConn); err != nil {
		conn.Close()
	}

	SendMessage(conn)

	readId := c.Query("readId")

	read, _ := strconv.Atoi(readId)

	sendId := c.Query("sendId")

	send, _ := strconv.Atoi(sendId)

	ReadMessage(conn, read, send)

}

func SendMessage(conn *pkg.Connection) {
	go func() {
		for {
			if err = conn.WriteMessage([]byte("heartbeat")); err != nil {
				conn.Close()
				return
			}
			time.Sleep(time.Second * 10)
		}
	}()
}

func ReadMessage(conn *pkg.Connection, readId, sendId int) {
	for {
		if data, err = conn.ReadMessage(); err != nil {
			conn.Close()
			return
		}
		message := CreateMessage(data, sendId, readId)
		if message != "" {
			conn.Close()
		}
		if err = conn.WriteMessage(data); err != nil {
			conn.Close()
			return
		}
	}
}
